package tenumn.energytech.registrys.capability;


import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.item.Item;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityProvider;
import net.minecraftforge.common.util.INBTSerializable;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.energy.CapabilityEnergy;
import net.minecraftforge.energy.EnergyStorage;
import net.minecraftforge.energy.IEnergyStorage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.function.Supplier;

public class EnergyCapabilityProvider extends CapabilityProvider<EnergyCapabilityProvider> implements INBTSerializable<CompoundTag> {

    private final LazyOptional<EnergyStorage> capability;

    public EnergyCapabilityProvider(Supplier<EnergyStorage> supplier) {
        super(EnergyCapabilityProvider.class);
        capability = LazyOptional.of(supplier::get);
    }


    @Override
    public <T> LazyOptional<T> getCapability( Capability<T> cap,  Direction side) {
        return CapabilityEnergy.ENERGY.orEmpty(cap, capability.cast());
    }

    @Override
    public CompoundTag serializeNBT() {
        CompoundTag tag=new CompoundTag();
        if (capability.resolve().isPresent())  tag.put("FE",capability.resolve().get().serializeNBT());
        return tag;
    }

    @Override
    public void deserializeNBT(CompoundTag nbt) {
        if (nbt.contains("FE"))
            capability.ifPresent(cap -> cap.deserializeNBT(nbt.get("FE")));
    }
}
